package com.gin.kotlin.gf2gamecommunity.routes

import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.AssistChip
import androidx.compose.material3.AssistChipDefaults
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SuggestionChip
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import androidx.navigation.toRoute
import com.gin.kotlin.form.PrivacyForm
import com.gin.kotlin.gf2gamecommunity.R
import com.gin.kotlin.gf2gamecommunity.app.App
import com.gin.kotlin.gf2gamecommunity.base.composable.BorderCard
import com.gin.kotlin.gf2gamecommunity.base.composable.MyImage
import com.gin.kotlin.gf2gamecommunity.base.composable.TabInfo
import com.gin.kotlin.gf2gamecommunity.base.composable.TabRowPager
import com.gin.kotlin.gf2gamecommunity.base.util.copyText
import com.gin.kotlin.gf2gamecommunity.viewmodel.GameInfoViewModel
import com.gin.kotlin.response.game.GameInfo
import com.gin.kotlin.response.game.Heroine
import com.gin.kotlin.response.game.StageInfo
import com.gin.kotlin.response.game.StageInfoBody
import kotlinx.serialization.Serializable


fun NavGraphBuilder.gameInfo(onPopBackStack: () -> Unit, onNavigateToHeroineList: (route: HeroineListRoute) -> Unit) = composable<GameInfoRoute>(
    // 从屏幕右侧进入，持续500毫秒
    enterTransition = { slideInHorizontally(tween(500)) { it } },
    // 从屏幕右侧退出，持续500毫秒
    exitTransition = { slideOutHorizontally(tween(500)) { it } },
) {
    GameInfoComposable(route = it.toRoute(), onPopBackStack = onPopBackStack, onNavigateToHeroineList = onNavigateToHeroineList)
}

@Serializable
data class GameInfoRoute(val uid: Int)

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun GameInfoComposable(
    route: GameInfoRoute,
    viewModel: GameInfoViewModel = viewModel(),
    onPopBackStack: () -> Unit,
    onNavigateToHeroineList: (route: HeroineListRoute) -> Unit
) {
    val context = LocalContext.current
    val isCurrent = App.INSTANCE.currentAccount()?.uid == route.uid
    // 请求使用的uid ，如果是当前用户，置空
    val requestUid = if (isCurrent) null else route.uid
    val state = viewModel.gameInfo.fetch(requestUid).observeAsState()
    val gameInfo = state.value?.data
    Scaffold(
        topBar = {
            TopAppBar(navigationIcon = {
                IconButton(onClick = { onPopBackStack() }) {
                    Icon(imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "后退")
                }
            }, actions = {
                IconButton(onClick = {
                    context.copyText("${App.HOST}/m/otherData?id=${route.uid}", "已复制地址")
                }) {
                    Icon(painterResource(R.drawable.ic_content_copy_24), contentDescription = "复制地址")
                }
            }, title = {
                Text("游戏数据")
            })
        },

        ) { paddingValues ->
        val modifier = Modifier.padding(paddingValues)
        // 切换显示状态时
        val onSwitchChanged: (type: Int) -> Unit = { viewModel.setDisplay(requestUid, PrivacyForm(it)) }
        Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
            if (gameInfo == null) CircularProgressIndicator() else gameInfo.apply {
                Column(modifier = Modifier
                    .fillMaxSize()
                    .padding(8.dp)) {
                    // 玩家数据
                    UserInfo(userInfo = userInfo)

                    val tabList = mutableListOf<TabInfo>()
                    userInfo.apply {
                        if (showBase || showHero || isCurrent) tabList.add(TabInfo("基础", R.drawable.ic_dashboard_24) {
                            Column {
                                Text("基础资料", fontWeight = FontWeight.Bold, fontSize = 18.sp)
                                BaseInfoCard(baseInfo = baseInfo, show = userInfo.showBase, isCurrent = isCurrent, onSwitchChanged = onSwitchChanged)
                                Spacer(modifier = Modifier.height(8.dp))
                                Text("人形展示", fontWeight = FontWeight.Bold, fontSize = 18.sp)
                                HeroInfoCard(heroList = heroList.sortedBy { it.serialId }, show = userInfo.showHero, isCurrent = isCurrent, onSwitchChanged = onSwitchChanged,
                                    onNavigateToHeroineList = onNavigateToHeroineList)
                            }
                        })
                        if (showStage || isCurrent) tabList.add(TabInfo("战绩", R.drawable.ic_checklist_rtl_24) {
                            StageInfoCard(stageInfo = stageInfo, show = userInfo.showStage, isCurrent = isCurrent, onSwitchChanged = onSwitchChanged)
                        })
                        if (showTheme || isCurrent) tabList.add(TabInfo("活动", R.drawable.ic_event_note_24) {
                            ThemeInfoCard(themeInfo = themeInfo, show = userInfo.showTheme, isCurrent = isCurrent, onSwitchChanged = onSwitchChanged)
                        })
                    }
                    TabRowPager(tabList, beyondViewportPageCount = 1)
                }
            }
        }
    }
}

/**
 * 顶部账号信息卡
 * @param userInfo GameInfo.UserInfo
 * @param modifier Modifier
 */
@Composable
private fun UserInfo(userInfo: GameInfo.UserInfo, modifier: Modifier = Modifier) {
    val context = LocalContext.current
    userInfo.apply {
        Card(
            modifier = Modifier.fillMaxWidth(),
            border = BorderStroke(2.dp, CardDefaults.cardColors().disabledContentColor),
        ) {
            Row(horizontalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.padding(8.dp)) {
                Column(horizontalAlignment = Alignment.CenterHorizontally) {
                    MyImage(model = avatar, modifier = Modifier
                        // .clip(CircleShape)
                        .width(80.dp))
                    SuggestionChip(onClick = { }, label = { Text("Lv. $level") })
                }
                Column {
                    Text(userInfo.nickName, fontSize = 20.sp)
                    AssistChip(onClick = {
                        context.copyText(userInfo.gameUid.toString(), "已复制UID")
                    }, label = { Text(gameUid.toString()) }, leadingIcon = {
                        Icon(painterResource(R.drawable.ic_content_copy_24), contentDescription = "复制uid", Modifier.size(AssistChipDefaults.IconSize))
                    })
                    if (guildName.isNotEmpty()) Text("班组: $guildName")
                }
            }
        }
    }
}

@Composable
private fun BaseInfoCard(baseInfo: GameInfo.BaseInfo, show: Boolean, isCurrent: Boolean, onSwitchChanged: (type: Int) -> Unit, modifier: Modifier = Modifier) {
    val data = hashMapOf<String, String>()
    baseInfo.apply {
        data["人形收集数"] = heroCount.toString()
        data["活跃天数"] = activeDays.toString()
        data["主线进度"] = mainStage
        data["衣装收集数"] = skinCount.toString()
        data["武器收集数"] = weaponCount.toString()
        data["里程碑"] = achievementCount.toString()
    }
    Column {
        if (isCurrent) Switch(show, onCheckedChange = { _ -> onSwitchChanged(1) })
        LazyVerticalGrid(columns = GridCells.Adaptive(minSize = 128.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
            items(items = data.entries.toList()) { (k, v) -> BaseInfoGridCard(v, k) }
        }
    }
}

@Composable
private fun BaseInfoGridCard(textTop: String, textBottom: String) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        border = BorderStroke(2.dp, CardDefaults.cardColors().disabledContentColor),
    ) {
        Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier
            .padding(8.dp)
            .fillMaxWidth()) {
            Text(textTop)
            Text(textBottom)
        }
    }
}


@Composable
private fun HeroInfoCard(
    heroList: List<Heroine>,
    show: Boolean,
    isCurrent: Boolean,
    onSwitchChanged: (type: Int) -> Unit,
    modifier: Modifier = Modifier,
    onNavigateToHeroineList: (route: HeroineListRoute) -> Unit
) {
    Column {
        if (isCurrent) Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) {
            Switch(show, onCheckedChange = { _ -> onSwitchChanged(2) })
            Button(onClick = { onNavigateToHeroineList(HeroineListRoute()) }) { Text("修改") }
        }
        LazyVerticalGrid(columns = GridCells.Fixed(4), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
            items(items = heroList) { heroine -> HeroineGridCard(heroine) }
        }
    }
}

@Composable
fun HeroineGridCard(heroine: Heroine) {
    Box(
        contentAlignment = Alignment.BottomCenter,
        // modifier = Modifier.background(Color.Gray)
    ) {
        val scale = 0.55f
        MyImage(heroine.url(), modifier = Modifier
            .width((160 * scale).toInt().dp)
            .height((248 * scale).toInt().dp)
        )
        Text("Lv. ${heroine.heroLevel}", fontWeight = FontWeight.Bold, fontSize = 12.sp)
    }
}

@Composable
private fun StageInfoCard(stageInfo: StageInfoBody, show: Boolean, isCurrent: Boolean, onSwitchChanged: (type: Int) -> Unit, modifier: Modifier = Modifier) {
    Column {
        if (isCurrent) Switch(show, onCheckedChange = { _ -> onSwitchChanged(3) })
        TabRowPager(listOf(
            TabInfo("歧路挑战") {
                LazyColumn(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.padding(4.dp)) {
                    items(items = stageInfo.weekSpecial) { StageItem(it) }
                }
            },
            TabInfo("其他挑战") {
                Column(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.padding(4.dp)) {
                    StageItem(stageInfo.kuobianStage, nameColor = Color.White)
                    StageItem(stageInfo.towerStage, nameColor = Color.White)
                    StageItem(stageInfo.weekCommon)
                }
            },
        ), beyondViewportPageCount = 1)
    }
}

@Composable
fun StageItem(data: StageInfo, nameColor: Color = Color.Unspecified, modifier: Modifier = Modifier) {
    data.apply {
        BorderCard {
            Box(contentAlignment = Alignment.CenterEnd) {
                MyImage(showPic, modifier = modifier
                    .fillMaxWidth()
                    .height(110.dp))
                Column(modifier = Modifier.padding(4.dp), horizontalAlignment = Alignment.End) {
                    Text(name, fontSize = 22.sp, color = nameColor)
                    if (stayStage == 0) Text("未参与", color = Color.Red)
                    // else Text("最高分: $stayStage", color = nameColor)
                    if (!stageCode.isNullOrEmpty()) Text("$stageCode $stageName", color = Color.Red)
                    if (completePercent != null) Text("$completePercent%")
                    if (stageRank != null) Text("层级: ${stageRank?.plus(1)}")
                }
            }

        }
    }
}


@Composable
private fun ThemeInfoCard(themeInfo: List<GameInfo.ThemeInfo>, show: Boolean, isCurrent: Boolean, onSwitchChanged: (type: Int) -> Unit, modifier: Modifier = Modifier) {
    Column {
        if (isCurrent) Switch(show, onCheckedChange = { _ -> onSwitchChanged(4) })

        LazyVerticalGrid(verticalArrangement = Arrangement.spacedBy(4.dp),
            horizontalArrangement = Arrangement.spacedBy(4.dp),
            modifier = Modifier.padding(4.dp),
            columns = GridCells.Adaptive(minSize = 160.dp)) {
            items(items = themeInfo) { ThemeInfoItem(it) }
        }
    }
}

@Composable
private fun ThemeInfoItem(item: GameInfo.ThemeInfo, modifier: Modifier = Modifier) {
    item.apply {
        BorderCard {
            Box(contentAlignment = Alignment.BottomCenter) {
                MyImage(showPic, modifier = modifier
                    .fillMaxWidth()
                    .height(110.dp))
                Text("$completePercent%")
            }
        }
    }
}